<?php

/**
 * uvmcSolrSearchableTemplate class
 *
 * @package uvmcSolrSearchPlugin
 * @subpackage behavior
 * @author Marc Weistroff <mweistroff@uneviemoinschere.com>
 * @version $Id: uvmcSolrSearchableTemplate.class.php 5 2009-09-15 16:40:12Z marc.weistroff $
 *
 **/
class uvmcSolrSearchable extends Doctrine_Template 
{
  protected
    $_eventName,
    $_highlight = '',
    $_options = array();
    
  public function __construct(array $options = array())
  {
    $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
  }
  
  /**
   * @param string $uniqueIdColumn
   * @param array $uniqueIds
   * @return Doctrine_Query
   */
  public function getBaseQueryForSolrResultsTableProxy($uniqueIdColumn, $uniqueIds)
  {
    $t = $this->getTable();
    $q = $t->createQuery('s')->select('s.*');
    
    if(empty($uniqueIds))
    {
      $q->andWhereIn('s.'.$uniqueIdColumn, -1);
    }
    else
    {
      $q->andWhereIn('s.'.$uniqueIdColumn, $uniqueIds)
        ->addSelect('FIELD(s.'.$uniqueIdColumn.','.implode(',', $uniqueIds).') AS solr_field')
        ->orderBy('solr_field');
    }
    
    return $q;
  }
  
  public function getHighlight()
  {
    return $this->_highlight;
  }
  
  public function setHighlight($highlight)
  {
    $this->_highlight = $highlight;
  }
  
  /**
   * @return array
   */
  public function getSolrDocumentFields()
  {
    $record = $this->getInvoker();
    $solrFields = array();
    
    foreach ($this->_options['fields'] as $field => $fieldOptions)
    { 
      if (!isset($fieldOptions['local']) && !isset($fieldOptions['method']))
      {
        throw new sfException(sprintf("Field %s requires a 'local' or 'method' option.", $field));
      }
      
      $localResult = isset($fieldOptions['method']) ? $record->{$fieldOptions['method']}() : $record->{$fieldOptions['local']};
      $boost = isset($fieldOptions['boost']) ? $fieldOptions['boost'] : false;
      
      $value = array();
      if (!isset($fieldOptions['multi_valued']))
      {
        $value = $boost === false ? $localResult : array('value' => $fieldValue, 'boost' => $boost);
      }
      else
      {
        foreach($localResult as $result)
        {
          $value[] = $boost === false ? $result : array('value' => $result, 'boost' => $boost);
        }
      }
      
      $solrFields[$field] = $value;
    }
    
    return $solrFields;
  }
}